package com.xigege.netty.TCPStickyBag.solve.presetLength;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.Random;


/**
 * @author huangxi
 * @class StickHalfBagClient
 * @description StickHalfBagClient
 * @create 2022-08-23 15:03
 */
public class PresetLengthClient {

    public static void sendMsg(ByteBuf buffer, String content) {
        int version = 2;
        byte[] msgByte = content.getBytes();
        buffer.writeInt(msgByte.length);
        buffer.writeInt(version);
        buffer.writeBytes(msgByte);
    }

    public static void main(String[] args) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ChannelFuture future = new Bootstrap()
                    .group(worker)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                // 连接建立好之后
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    ByteBuf buffer = ctx.alloc().buffer();
                                    sendMsg(buffer, "baby you are firework!");
                                    sendMsg(buffer, "Do you ever feel like a plastic bag~");
                                    ctx.writeAndFlush(buffer);
                                }
                            });
                        }
                    })
                    .connect(new InetSocketAddress("localhost", 6666))
                    .sync();
            Channel channel = future.channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
